import React, { useState, useEffect, useRef, useCallback } from 'react';
import { LazyLog } from 'react-lazylog';
import SearchBar from './SearchBar';

const LogViewer = ({ content: initialContent = '', logType: initialLogType = '', fileName = '' }) => {
  const [content, setContent] = useState(initialContent);
  const [logType, setLogType] = useState(initialLogType);
  const [searchTerm, setSearchTerm] = useState('');
  const [searchResults, setSearchResults] = useState([]);
  const [currentSearchIndex, setCurrentSearchIndex] = useState(-1);
  const [isSearchVisible, setIsSearchVisible] = useState(false);
  const [processedContent, setProcessedContent] = useState('');
  const lazyLogRef = useRef(null);

  // 监听 props 变化
  useEffect(() => {
    if (initialContent !== content) {
      setContent(initialContent);
    }
    if (initialLogType !== logType) {
      setLogType(initialLogType);
    }
  }, [initialContent, initialLogType]);

  // 语法高亮处理函数
  const applyLogHighlighting = useCallback((content, fileName) => {
    if (!content) return '';
    
    const lines = content.split('\n');
    const maxLines = 5000; // 限制处理行数以防止性能问题
    const processLines = lines.slice(0, maxLines);
    
    let highlightedLines = [];
    
    if (fileName && fileName.includes('crash-log')) {
      // 崩溃日志高亮
      highlightedLines = processLines.map(line => {
        const escapedLine = escapeHtml(line);
        if (line.includes('ERROR') || line.includes('FATAL')) {
          return `<span class="log-error">${escapedLine}</span>`;
        } else if (line.includes('WARNING') || line.includes('WARN')) {
          return `<span class="log-warning">${escapedLine}</span>`;
        } else if (line.includes('INFO')) {
          return `<span class="log-info">${escapedLine}</span>`;
        }
        return escapedLine;
      });
    } else if (fileName && fileName.includes('app-log')) {
      // 应用日志高亮
      highlightedLines = processLines.map(line => {
        const escapedLine = escapeHtml(line);
        
        // 解析日志结构：时间 + 等级 + TAG + 内容
        // 示例：2025.07.24 02:41:37.451 L:FILE SocketClientmain : 发送命令:{"id":27630,"method":"get_focuser_setting"}
        const logPattern = /^(\d{4}\.\d{2}\.\d{2}\s+\d{2}:\d{2}:\d{2}\.\d{3})\s+(L:\w+)\s+(\w+)\s*:\s*(.*)$/;
        const match = line.match(logPattern);
        
        if (match) {
          const [, timestamp, level, tag, content] = match;
          
          // 确定内容类型和对应的样式
          let contentClass = 'log-other';
          if (content.includes('接收事件')) {
            contentClass = 'log-event';
          } else if (content.includes('发送命令') || content.includes('接收命令')) {
            contentClass = 'log-command';
          }
          
          // 构建高亮的HTML
          return `<span class="log-timestamp">${escapeHtml(timestamp)}</span> <span class="log-level">${escapeHtml(level)}</span> <span class="log-tag">${escapeHtml(tag)}</span> : <span class="${contentClass}">${escapeHtml(content)}</span>`;
        }
        
        // 回退到简单的关键词高亮
        if (line.includes('ERROR') || line.includes('FATAL')) {
          return `<span class="log-error">${escapedLine}</span>`;
        } else if (line.includes('WARNING') || line.includes('WARN')) {
          return `<span class="log-warning">${escapedLine}</span>`;
        } else if (line.includes('INFO')) {
          return `<span class="log-info">${escapedLine}</span>`;
        } else if (line.includes('接收事件')) {
          return `<span class="log-receive">${escapedLine}</span>`;
        } else if (line.includes('发送命令')) {
          return `<span class="log-send">${escapedLine}</span>`;
        }
        
        return escapedLine;
      });
    } else {
      // 默认处理
      highlightedLines = processLines.map(line => escapeHtml(line));
    }
    
    return highlightedLines.join('\n');
  }, []);

  // HTML 转义函数
  const escapeHtml = (text) => {
    const div = document.createElement('div');
    div.textContent = text;
    return div.innerHTML;
  };

  // 处理内容变化
  useEffect(() => {
    const highlighted = applyLogHighlighting(content, fileName);
    setProcessedContent(highlighted);
  }, [content, fileName, applyLogHighlighting]);

  // 搜索功能
  const handleSearch = useCallback((term) => {
    setSearchTerm(term);
    
    if (!term.trim()) {
      setSearchResults([]);
      setCurrentSearchIndex(-1);
      return;
    }

    try {
      const regex = new RegExp(term.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'), 'gi');
      const lines = content.split('\n');
      const results = [];
      
      lines.forEach((line, lineIndex) => {
        let match;
        while ((match = regex.exec(line)) !== null) {
          results.push({
            lineIndex,
            columnIndex: match.index,
            text: match[0]
          });
        }
      });
      
      setSearchResults(results);
      setCurrentSearchIndex(results.length > 0 ? 0 : -1);
    } catch (error) {
      console.error('搜索错误:', error);
      setSearchResults([]);
      setCurrentSearchIndex(-1);
    }
  }, [content, onSearch]);

  // 导航到下一个搜索结果
  const navigateToNext = useCallback(() => {
    if (searchResults.length > 0) {
      const nextIndex = (currentSearchIndex + 1) % searchResults.length;
      setCurrentSearchIndex(nextIndex);
      
      // 滚动到对应行
      const result = searchResults[nextIndex];
      if (lazyLogRef.current && result) {
        // react-lazylog 的滚动到行功能
        lazyLogRef.current.scrollToLine(result.lineIndex + 1);
      }
    }
  }, [searchResults, currentSearchIndex]);

  // 导航到上一个搜索结果
  const navigateToPrevious = useCallback(() => {
    if (searchResults.length > 0) {
      const prevIndex = currentSearchIndex === 0 ? searchResults.length - 1 : currentSearchIndex - 1;
      setCurrentSearchIndex(prevIndex);
      
      // 滚动到对应行
      const result = searchResults[prevIndex];
      if (lazyLogRef.current && result) {
        lazyLogRef.current.scrollToLine(result.lineIndex + 1);
      }
    }
  }, [searchResults, currentSearchIndex]);

  return (
    <div className="react-log-viewer">
      <SearchBar
        onSearch={handleSearch}
        searchResults={searchResults}
        currentIndex={currentSearchIndex}
        onNext={navigateToNext}
        onPrevious={navigateToPrevious}
      />
      
      <div className="log-content-container">
        <LazyLog
          ref={lazyLogRef}
          text={processedContent}
          enableSearch={false}
          selectableLines={true}
          enableLineNumbers={true}
          height="auto"
          width="100%"
          caseInsensitive={true}
          extraLines={1}
          stream={false}
          follow={false}
          formatPart={(text) => {
            return text;
          }}
          style={{
            backgroundColor: '#1e1e1e',
            color: '#d4d4d4',
            fontFamily: 'Consolas, "Courier New", monospace',
            fontSize: '13px',
            lineHeight: '1.4'
          }}
        />
      </div>
    </div>
  );
};

export default LogViewer;